package com.nbsaas.boot;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

import java.io.*;
import java.net.InetSocketAddress;
import java.util.Map;

public class JacksonJsonWebServer {

    public static void main(String[] args) throws IOException {
        // 创建一个HttpServer，绑定到8080端口
        HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);

        // 设置一个处理器，处理根路径"/json"的请求
        server.createContext("/json", new HttpHandler() {
            @Override
            public void handle(HttpExchange exchange) throws IOException {
                // 仅处理POST请求
                if ("POST".equals(exchange.getRequestMethod())) {
                    // 读取请求体中的JSON数据
                    InputStream inputStream = exchange.getRequestBody();
                    String jsonRequest = readInputStream(inputStream);

                    // 使用Jackson ObjectMapper解析JSON
                    ObjectMapper objectMapper = new ObjectMapper();
                    Map<String, Object> requestMap = objectMapper.readValue(jsonRequest, Map.class);

                    // 从请求中获取"name"字段
                    String name = (String) requestMap.getOrDefault("name", "Unknown");

                    // 创建一个响应的Map
                    Map<String, Object> responseMap = Map.of(
                            "message", "Hello, " + name + "!",
                            "status", "success"
                    );

                    // 使用Jackson将Map转为JSON字符串
                    String responseJson = objectMapper.writeValueAsString(responseMap);

                    // 设置响应头，响应内容类型为application/json
                    exchange.getResponseHeaders().set("Content-Type", "application/json");

                    // 写入响应内容
                    exchange.sendResponseHeaders(200, responseJson.getBytes().length);
                    try (OutputStream os = exchange.getResponseBody()) {
                        os.write(responseJson.getBytes());
                    }
                } else {
                    // 如果请求不是POST方法，返回405 Method Not Allowed
                    String response = "{\"error\": \"Method Not Allowed\"}";
                    exchange.sendResponseHeaders(405, response.getBytes().length);
                    try (OutputStream os = exchange.getResponseBody()) {
                        os.write(response.getBytes());
                    }
                }
            }
        });

        // 启动服务
        server.start();
        System.out.println("Server is running on http://localhost:8080/json");
    }

    // 读取输入流中的数据并转换为字符串
    private static String readInputStream(InputStream inputStream) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            stringBuilder.append(line);
        }
        return stringBuilder.toString();
    }
}
